package com.yonyou.chuan.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yonyou.chuan.cache.CacheManager;
import com.yonyou.chuan.cache.CacheUtil;
import com.yonyou.chuan.constant.Constant;
import com.yonyou.chuan.log.LoggerUtil;

public class QxgTokenUtil {

    private static final CacheManager CACHEMANAGER = CacheUtil.getCacheManager();

    public static String getToken(String tokenApi,String appKey,String appSecret) {
        String token = CACHEMANAGER.get(Constant.QXG_TOKENKEY);
        if (token != null && !token.isEmpty()) {
            return token;
        }
        JSONObject tokenBody = new JSONObject();
        tokenBody.put("appKey", appKey);
        tokenBody.put("appSecret", appSecret);
        LoggerUtil.printLogger("【7小哥聚合平台系统Api鉴权】,请求地址: {}",tokenApi);
        String resp = HttpUtil.createPost(tokenApi)
                .header("Content-Type", "application/json")
                .body(tokenBody.toString())
                .execute()
                .body();
        LoggerUtil.printLogger("【7小哥聚合平台系统Api鉴权】,响应报文: {}", resp);
        if(Constant.QXG_SUCCESS_CODE == JSONUtil.parseObj(resp).getInt("code")){
            String refreshToken = JSONUtil.parseObj(resp).getJSONObject("data").getStr("api_access_token");
            CACHEMANAGER.put(Constant.QXG_TOKENKEY, refreshToken, Constant.ONE_HOUR_SECONDS_VALUE);
            return refreshToken;
        }
        throw new RuntimeException("【7小哥聚合平台系统Api鉴权】,响应失败:" + resp);
    }

}
